package com.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.bean.Msg;
import com.bean.User;
import com.bean.UserType;
import com.service.IUserService;
import com.shiro.token.CustomLoginToken;
import com.shiro.token.JWTToken;
import com.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录的controller
 * @author WxrStart
 * @create 2022-05-17 12:49
 */
@Slf4j
@Controller
public class LoginController {
    @Autowired
    IUserService iUserService;

    /**
     * 登录，并且进行JSR-303校验
     * @param loginuser
     * @return
     */
    @PostMapping(value = "/loginbyemail")
    @ResponseBody
    public Msg login(@RequestBody  User loginuser, BindingResult result, HttpServletResponse response) {
        log.info("提交用户名密码到了邮箱登录页");
        //JSR303校验逻辑
        if (result.hasErrors()) {
            Map<String, Object> map = new HashMap();
            //校验失败，返回错误信息给前端
            List<FieldError> errors = result.getFieldErrors();
            for (FieldError fieldErrors : errors) {
                map.put(fieldErrors.getField(), fieldErrors.getDefaultMessage());
            }
            return Msg.fail().add("errorFields", map);
        }
        String email = loginuser.getEmail();
        String password = loginuser.getPassword();
        User user = iUserService.findByEmail(email);
        if (user == null) {
            throw new UnknownAccountException();
        }
        //判断用户是否被冻结
        if (user.getStatus()!=1) {
            throw new LockedAccountException("该用户已被冻结,暂时无法登录！");
        }
        // 将用户名和密码封装成 UsernamePasswordToken 对象
        CustomLoginToken token = new CustomLoginToken(email,password,user.getUserRole());
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        // 若登录成功，签发 JWT token
        String jwtToken = JWTUtils.sign(email,user.getUserRole(),JWTUtils.SECRET);
        // 将签发的 JWT token 设置到 HttpServletResponse 的 Header 中
         response.setHeader(JWTUtils.AUTH_HEADER, jwtToken);
        return Msg.success().add("result","登陆成功").add("jwt",jwtToken);
    }

}
